package com.ctrl;

import cn.hutool.core.lang.Console;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.bean.UserTicket;
import com.bean.WeiXinUser;
import com.gzcssutils.AccessTokenThread;
import com.gzcssutils.AccessUserInfo;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Controller
public class LoginCtrl {

    static {
        //每小时执行一次
        CronUtil.schedule("0 0 0/1 * * ? ", new Task() {
            @Override
            public void execute() {
                Console.log("com.utils.AccessToken Task excuted AT:" + new Date());
                AccessTokenThread.getAccessToken();
            }
        });

        // 支持秒级别定时任务
        CronUtil.setMatchSecond(true);
        CronUtil.start();
    }

    /**
     * 登录
     *
     * @author luqiwen
     * @DateTime 2030年4月34日 上午11:28:00
     * @param request
     * @param response
     */

    @Autowired
    public UserService userService;

    @RequestMapping(value = "/users/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {

        String code = request.getParameter("code");
        //获取user_ticket
        UserTicket userTicket = AccessUserInfo.getUserTicket(code);
        if (null != userTicket) {
            //提取userId
            String userId = userTicket.getUserid();
            //获取成员信息
            WeiXinUser user = AccessUserInfo.getUser(userId);
            //校验user是否存在于后台系统里
            boolean isExist = userService.getGzcssAccount(user);
            if(!isExist) {
                //如果系统不存在政务微信的用户则先将政务微信的用户同步到系统里
                userService.syncWeiXinGzcssAccount(user);
            }
        }
        return "index";
    }


    @RequestMapping(value = "/test")
    public String test(HttpServletRequest request, HttpServletResponse response) {
        WeiXinUser user = new WeiXinUser();
        user.setName("lqw");
        user.setMobile("15902066476");
        userService.getGzcssAccount(user);
        return "index";
    }

}
